package com.collectplus.express;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;

import com.baidu.mapapi.SDKInitializer;
import com.collectplus.express.evaluate.EvaluateActivity;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.model.PushMessageModel;
import com.collectplus.express.order.OrderPayActivity;
import com.collectplus.express.parcel.ParcelDetailActivity;
import com.shouhuobao.bhi.coupon.CouponListActivity;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.tencent.android.tpush.XGPushConfig;
import com.umeng.analytics.MobclickAgent;

import java.lang.Thread.UncaughtExceptionHandler;

import droid.frame.App;
import droid.frame.push.PushMsgID;
import droid.frame.utils.CrashHandler;
import droid.frame.utils.android.Log;
import droid.frame.utils.lang.JsonParser;

public class ExpressApplication extends App {

    private static ExpressApplication mInstance = null;

    private NotificationManager nm;

    private CrashHandler crashHandler;

    private RefWatcher refWatcher;

    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return crashHandler;
    }

    public static RefWatcher getRefWatcher(Context context) {
        ExpressApplication application = (ExpressApplication) context.getApplicationContext();
        return application.refWatcher;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        AppConfig.init();
        if (null == nm) {
            nm = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        }
        // umeng禁止默认的页面统计
        MobclickAgent.openActivityDurationTrack(false);
        // 发送策略 （1）在没有获取到在线配置时，默认使用启动时发送的策略。
        //（2）在打开debug调试模式或者使用集成测试时，不受发送策略控制。
        //		MobclickAgent.updateOnlineConfig(this);
        MobclickAgent.setCatchUncaughtExceptions(true);
        // 初始化百度地图
        SDKInitializer.initialize(this);

        crashHandler = new CrashHandler(getContext());
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
        //开启信鸽的日志输出，线上版本不建议调用
        XGPushConfig.enableDebug(this, AppConfig.isTest);
        refWatcher = LeakCanary.install(this);

        // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()//
        // .detectAll().penaltyLog().build());
        // // StrictMode VmPolicy violation with POLICY_DEATH; shutting down. 百度地图
        // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }

    public static ExpressApplication getInstance() {
        return mInstance;
    }

    @SuppressLint("HandlerLeak")
    protected void onCreateHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case PushMsgID.message_recv:
                        if (AppCache.isLogin() == false) {
                            return;
                        }
                        PushMessageModel item = JsonParser.parse(msg.obj + "", PushMessageModel.class);
                        Log.d("jpush", "-----------jpush-------" + msg.obj);
                        if (item != null) {
                            Class<?> activityClass = null;
                            switch (item.getType()) {
                                //邮票即将过期
                                case 1:
                                    if (activityClass == null) {
                                        activityClass = CouponListActivity.class;
                                    }
                                case 8:
                                    if (activityClass == null) {
                                        activityClass = ParcelDetailActivity.class;
                                    }
                                    //						case 10:// 包裹详情
                                    //							activityClass = ParcelDetailActivity.class;
                                case 11:// 服务评价
                                    if (activityClass == null) {
                                        activityClass = EvaluateActivity.class;
                                    }
                                case 12:
                                    if (activityClass == null) {
                                        activityClass = OrderPayActivity.class;
                                    }
                                    Intent intent = new Intent();
                                    intent.setClass(getContext(), activityClass);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);// 启动模式不一样
                                    Bundle bundle = new Bundle();
                                    bundle.putString("orderId", item.getOrderId());
                                    bundle.putString("parcelId", item.getParcelId() + "");
                                    intent.putExtra("parcelBundle", bundle);
                                    sendNotification(getContext(), item.getDescription(), intent);
                                    break;
                                default:
                                    sendNotification(getContext(), item.getDescription(), null);
                                    break;
                            }

                        }
                        break;
                    case PushMsgID.message_token:
                        String token = (String) msg.obj;
                        if (AppCache.getUserId() != 0) {
                            AppHttp.getInstance().updatePushToken(token);
                        }
                        break;
                }
            }
        };
    }


    private void sendNotification(Context context, String message, Intent intent) {
        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(context);
        notifyBuilder.setContentTitle(context.getResources().getString(R.string.app_name));
        notifyBuilder.setContentText(message);
        notifyBuilder.setSmallIcon(R.drawable.ic_launcher);
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
        notifyBuilder.setLargeIcon(bitmap);
        // 这里用来显示右下角的数字
        // notifyBuilder.setNumber(10);
        notifyBuilder.setWhen(System.currentTimeMillis());
        notifyBuilder.setAutoCancel(true);

        notifyBuilder.setDefaults(Notification.DEFAULT_ALL);

        if (intent == null) {
            intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            // 使用传入的 intent
        }
        // Creates the PendingIntent
        // 当设置下面PendingIntent.FLAG_UPDATE_CURRENT这个参数的时候，常常使得点击通知栏没效果，你需要给notification设置一个独一无二的requestCode
        int requestCode = (int) SystemClock.uptimeMillis();
        PendingIntent pendIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notifyBuilder.setContentIntent(pendIntent);
        nm.notify(R.string.app_name, notifyBuilder.build());
    }
}
